import axios from 'axios'
import Vue from 'vue'
import App from '../App.vue'
import router from '../router'

var _this = new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

axios.defaults.baseURI = '/api/'
// 设置超时请求时间
axios.default.timeout = 1000

// axios.defaults.headers['Content-Type'] = 'application/x-www-from-urlencoded'
axios.defaults.headers['Content-Type'] = 'application/json'

// 设置响应拦截器
axios.interceptors.response.use(
  response => {
    // 返回响应主体中的信息，例如知道服务器返回CODE值来确定成功还是失败
    console.log('response.data:', response.data)
    return response.data
  },
  error => {
    _this.$dialog.alert({
      message: '身份已失效'
    })
    // 清除token
    window.localStorage.removeItem('loginToken')
    // 跳转到登陆页
    _this.$router.push({
      name: 'Login'
    }).catch(err => {
      console.log('err:', err)
    })
    console.log('error:', Promise.reject(error))
    return Promise.reject(error)
  }
)

// 设置请求拦截器
axios.interceptors.request.use(
  config => {
    const storage = window.localStorage
    if (storage.getItem('loginToken')) {
      // 在请求头中加入token
      config.headers.token = JSON.parse(storage.getItem('loginToken')).token
    }
    console.log('config:', config)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

export default axios
